package de.koller.singularity.engine.tile;

import de.koller.aframe.util.resource.IOLoader;
import de.koller.oceanFramework.OceanException;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class TileCreator {

	private final Map<String, STile> tiles = new HashMap<>();

	public TileCreator() {
		try {
			loadTiles();
		} catch( IOException ex ) {
			System.err.println( ex );
		}
	}
	
	public STile getTile( String name ) {
		return tiles.get( name );
	}
	
	private void loadTiles() throws IOException {
		BufferedImage ti = IOLoader.loadLocalImage( "./gameData/singularity/tiles.png" );
		File f = new File( "./gameData/singularity/tileConfig.kd" );
		BufferedReader o = new BufferedReader( new InputStreamReader( new FileInputStream( f ) ) );

		String s;
		while( (s = o.readLine()) != null ) {
			if( s.startsWith( "//" ) ) continue;
			
			if( s.startsWith( "T" ) ) {
				StringTokenizer st = new StringTokenizer( s );
				st.nextToken();
				int sx = Integer.parseInt( st.nextToken() );
				int sy = Integer.parseInt( st.nextToken() );
				String n = st.nextToken();
				
				createTile( sx, sy, n, ti );
			}
		}
		
	}
	
	private void createTile( int sx, int sy, String name, BufferedImage t ) {
		if( tiles.containsKey( name ) )
			throw new OceanException( name + " already a tilename!" );
		
		STile s = new STile( name );
		for( int x = 0; x < s.sprite.width; x++ )
			for( int y = 0; y < s.sprite.height; y++ )
				s.sprite.raster.setPixel( t.getRGB( sx+x, sy+y ), x, y );
		s.recalcColor();
		tiles.put( name, s );
	}
	
}
